package com.zbec.mdrs.web;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zbec.mdrs.license.LicenseCheckUtil;
import com.zbec.mdrs.license.parser.License;
import com.zbec.mdrs.service.LicenseRegisterService;
import com.zbec.mdrs.util.DateUtils;
import com.zbec.mdrs.vo.LicenseVO;

@Controller
public class LicenseRegisterController {
	
	
	@Autowired
	private LicenseRegisterService licenseRegisterService;
	
	@Autowired
	private LicenseCheckUtil licenseCheckUtil;
	
	@RequestMapping(value = "/license/register")
    public String licenseRegisterInit(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		License license = licenseRegisterService.getLicense();
		if(license != null && license.getStartDate() != null && license.getExpireInDays() != null){
			Date expireDate = DateUtils.addDaysToDate(
					DateUtils.toDate(license.getStartDate(), "yyyyMMdd"),
					Integer.parseInt(license.getExpireInDays()));
			map.put("expireDate", DateUtils.convertDateToString("yyyyMMdd", expireDate));
		}
		request.setAttribute("map", map);
        return "license/register";
    }
	
	@RequestMapping(value = "/license/register/save")
	@ResponseBody
	public String register(HttpServletRequest request, LicenseVO licenseVO) {
		if(licenseVO == null || licenseVO.getLicenseText() == null){
			return "N1";
		}
		if(licenseRegisterService.checkLicense(licenseVO.getLicenseText().trim())){
			return "N2";
		}
		licenseRegisterService.saveLicense(licenseVO.getLicenseText().trim());
		return "success";
	}
	
	@RequestMapping(value = "/license/check")
	@ResponseBody
	public String check(HttpServletRequest request, LicenseVO licenseVO) {
		String result = licenseCheckUtil.checkLicense();
		return result;
	}
}
